package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.dto.CollectDto;
import com.legal.aid.app.domain.vo.CollectVo;
import com.legal.aid.app.mapper.AppCollectMapper;
import com.legal.aid.app.service.IAppCollectService;
import com.legal.aid.common.core.domain.model.AppLoginUser;
import com.legal.aid.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class AppCollectServiceImpl implements IAppCollectService {

    @Autowired
    private AppCollectMapper appCollectMapper;

    @Override
    public boolean checkStatus(Long targetId, String targetType) {
        if (targetId == null || targetType == null) {
            return false;
        }
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            return false; // 用户未登录，无法检查收藏状态
        }
        Long userId = appLoginUser.getUserId();
        return appCollectMapper.checkCollectStatus(targetType, targetId, userId) != null;
    }

    @Override
    @Transactional
    public String add(CollectDto collectDto) {
        if (collectDto.getTargetId() == null || collectDto.getTargetType() == null) {
            return "收藏失败：参数错误";
        }
        String targetType = collectDto.getTargetType();

        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            return "收藏失败：请先登录";
        }
        Long userId = appLoginUser.getUserId();
        String createdBy = appLoginUser.getUsername();
        if (createdBy == null || createdBy.isEmpty()) {
            createdBy = String.valueOf(userId);
        }

        // 检查是否存在任何状态的收藏记录
        CollectVo existingCollect = appCollectMapper.checkAnyCollectStatus(targetType, collectDto.getTargetId(), userId);

        if (existingCollect != null) {
            // 如果已存在且未删除，则返回已收藏
            if ("0".equals(existingCollect.getIsDeleted())) {
                return "已收藏";
            } else if ("1".equals(existingCollect.getIsDeleted())) {
                // 如果已逻辑删除，则恢复收藏
                int result = appCollectMapper.recoverCollect(targetType, collectDto.getTargetId(), userId, createdBy);
                return result > 0 ? "收藏成功" : "收藏失败：恢复失败";
            }
        }

        // 如果不存在任何收藏记录，则添加新的收藏
        try {
            CollectDto newCollectDto = new CollectDto();
            newCollectDto.setUserId(userId);
            newCollectDto.setTargetId(collectDto.getTargetId());
            newCollectDto.setTargetType(targetType);
            newCollectDto.setCreatedBy(createdBy);
            
            int result = appCollectMapper.addCollect(newCollectDto);
            return result > 0 ? "收藏成功" : "收藏失败";
        } catch (DuplicateKeyException e) {
            // 如果发生唯一键冲突，说明记录已存在，尝试恢复
            int result = appCollectMapper.recoverCollect(targetType, collectDto.getTargetId(), userId, createdBy);
            return result > 0 ? "收藏成功" : "收藏失败：恢复失败";
        }
    }

    @Override
    @Transactional
    public String cancel(CollectDto collectDto) {
        if (collectDto.getTargetId() == null || collectDto.getTargetType() == null) {
            return "取消失败：参数错误";
        }
        String targetType = collectDto.getTargetType();

        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        if (appLoginUser == null || appLoginUser.getUserId() == null) { // 检查用户ID，username可以为空但我们将提供默认值
            return "取消失败：请先登录"; // 用户未登录
        }
        Long userId = appLoginUser.getUserId();
        String updatedBy = appLoginUser.getUsername();
        if (updatedBy == null || updatedBy.isEmpty()) { // 如果username为空，使用userId作为updatedBy
            updatedBy = String.valueOf(userId);
        }

        // 检查是否存在任何状态的收藏记录
        CollectVo existingCollect = appCollectMapper.checkAnyCollectStatus(targetType, collectDto.getTargetId(), userId);

        if (existingCollect == null) {
            // 记录完全不存在，视为已取消
            return "已取消";
        } else if ("1".equals(existingCollect.getIsDeleted())) {
            // 记录已存在且已逻辑删除，直接返回已取消
            return "已取消";
        }
        
        try {
            int result = appCollectMapper.deleteCollect(targetType, collectDto.getTargetId(), userId, updatedBy);
            return result > 0 ? "取消成功" : "取消失败";
        } catch (DuplicateKeyException e) {
            // 如果在更新时发生重复键异常，说明数据库中已存在is_deleted='1'的记录。
            // 从用户角度看，可以视为已成功取消。
            System.err.println("尝试取消收藏时捕获到重复键异常，可能原因为数据库存在冲突数据： " + e.getMessage());
            return "已取消"; // 视为成功
        } catch (Exception e) {
            System.err.println("取消收藏时发生未知异常： " + e.getMessage());
            return "取消失败";
        }
    }

    @Override
    @Transactional
    public boolean toggle(CollectDto collectDto) {
        if (collectDto.getTargetId() == null || collectDto.getTargetType() == null) {
            return false;
        }
        String targetType = collectDto.getTargetType();

        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            return false; // 用户未登录
        }

        // 检查当前状态
        boolean isCollected = checkStatus(collectDto.getTargetId(), targetType);
        
        // 根据当前状态执行相反的操作
        if (isCollected) {
            return "取消成功".equals(cancel(collectDto));
        } else {
            return "收藏成功".equals(add(collectDto));
        }
    }
}
